// 如果已登录，则访问首页、登录、注册和密码重置页面时会自动跳转至用户首页
import React from 'react';
import {connect} from 'react-redux';
import {push} from 'react-router-redux';

export function redirectAuthToHome(Component) {
  class AuthToHomeContainer extends React.Component {
    componentWillMount () {
      this.checkAuth(this.props.isAuthenticated);
    }

    componentWillReceiveProps (nextProps) {
      this.checkAuth(nextProps.isAuthenticated);
    }

    componentDidMount () {
      this.checkAuth(this.props.isAuthenticated);
    }

    checkAuth (isAuthenticated) {
      if (isAuthenticated) {
        let pathname = this.props.location.pathname;
        if (pathname == '/' || pathname =='/login' || pathname == '/register') {
          this.props.dispatch(push('/i'));
        }
      }
    }

    render() {
      return (
        <div style={{width: '100%'}}>
          <Component {...this.props}/>
        </div>
      );
    }
  }

  const mapStateToProps = (state) => ({
    isAuthenticated: state.login.isAuthenticated
  });

  return connect(mapStateToProps)(AuthToHomeContainer);
}
